import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://120.24.171.137:1337', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.state.user.token) {
      const logintime = localStorage.getItem('logintime')
      if (Date.now() - logintime > 86400000) {
        // 主动介入 token 失效步骤二, 每次注入token之前校验是否超时
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token已超时，请重新登录'))
      }
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  res => {
    // console.log(44, '请求层面成功', res)
    // console.log(res)
    // const { confirmed, message } = res.data
    const { statusText } = res
    if (statusText === 'OK') {
      // console.log('数据层面成功', statusText)
      return res.data
    } else {
      // console.log('数据层面失败')
      // Message.error(message)
      return Promise.reject(new Error('请求数据失败'))
    }
  }, err => {
    console.log(57, err)
    if (err.response && err.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('/login')
    }
    console.dir(51, err)
    Message.error(err.message)
    return Promise.reject(new Error(err))
  }
)

export default service
